const jwt=require("jsonwebtoken")

const {TOKEN_LIST,TOKEN_KEY}=require("../config/index")

module.exports = (options) => {
    return async function auth(ctx, next) {
      const {url}=ctx.request;
      const flag=TOKEN_LIST.includes(url)
      if(!flag){
        const token=ctx.request.headers["authorization"]
        if(token){
            const {exp}=jwt.verify(token,TOKEN_KEY)
            if(+new Date()>exp){
                ctx.status=401
                ctx.body={
                    code:"1002",
                    msg:"token已失效"
                }
            }else{
                await next()
            }
        }else{
            ctx.status=401
            ctx.body={
                code:"1002",
                msg:"token不存在"
            }
        }
      }else{
          await next()
      }
    }
  }